﻿using System.Collections.Generic;
using System.Reflection;
using SimpleOrmCFPC.Core.Model;
using SimpleOrmCFPC.Helpers;
using SimpleOrmCFPC.upgrade;

namespace SimpleOrmCFPC.Core.RequestsComputer
{
    public class SchemaFromTypeExtractor
    {
        public TableMapping Extract<T>()
        {
            string tableName = typeof(T).GetEntityName();
            var columns = new List<ColumnMapping>();

            foreach (var property in typeof(T).GetProperties())
            {
                string columnName = property.Name;
                if (property.HasAttribute<ManyToOneAttribute>())
                    columnName = property.Name + "Id";
                columns.Add(new ColumnMapping(columnName,
                                           IsPk(property),
                                           IsNotNull(property),
                                           IsAutoInc(property),
                                           property.PropertyType.ToDbType(),
                                           GetMaxLength(property)));
            }
            return new TableMapping()
                {
                    Name = tableName,
                    Columns = columns
                };
        }

        private bool IsPk(PropertyInfo p)
        {
            return p.GetCustomAttributes(typeof(PrimaryKeyAttribute), true).Length > 0;
        }

        private bool IsAutoInc(PropertyInfo p)
        {
            return p.GetCustomAttributes(typeof(AutoIncrementAttribute), true).Length > 0;
        }

        private bool IsNotNull(PropertyInfo p)
        {
            return p.GetCustomAttributes(typeof(NotNullAttribute), true).Length > 0;
        }

        private bool IsIndexed(PropertyInfo p)
        {
            return p.GetCustomAttributes(typeof(IndexedAttribute), true).Length > 0;
        }

        private int GetMaxLength(PropertyInfo property)
        {
            object[] attrs = property.GetCustomAttributes(typeof(MaxLengthAttribute), true);
            return attrs.Length > 0 ? ((MaxLengthAttribute)attrs[0]).Length : 255;
        }
    }
}